package com.nulldev.util.net.packets.npcrypt;

import com.nulldev.util.io.MD5Utils;
import com.nulldev.util.logging.LoggerFactory;
import com.nulldev.util.net.packets.APILevel;
import com.nulldev.util.net.packets.NetInfo;
import com.nulldev.util.net.packets.UniversalPacket;
import com.nulldev.util.other.ByteUtils;

@APILevel(level = 4)
public class NPCryptPublicKey extends UniversalPacket {

	/**
	 * NPCrypt PublicKey <br>
	 * data = Key in base64
	 */
	public NPCryptPublicKey() {
		super("nPacket v2+: Packet Encryption: RSA Public Key", "npcrypt.public", "");
	}

	@Override
	public void client(byte[] data, byte[] raw, NetInfo client) {
		final String key = createString(data);
		final byte[] keyData = ByteUtils.fromBase64(key);
		final boolean out = client.setServerPublicKey(keyData);
		if (out) {
			logger().trace("[NP.Crypt] RSA key recieved!");
			logger().trace("[NP.Crypt] Public Key MD5: " + MD5Utils.getMD5Hex(keyData));
		}
	}

	@Override
	public void server(byte[] data, byte[] raw, NetInfo connection) {
		final String key = createString(data);
		final byte[] keyData = ByteUtils.fromBase64(key);
		final boolean out = connection.setPublicKey(keyData);
		if (out) {
			logger().debug("[NP.Crypt] RSA key recieved!");
			logger().debug("[NP.Crypt] Public Key MD5: " + MD5Utils.getMD5Hex(keyData));
		}
	}

}
